﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Windvoice.Blog;

namespace Windvoice.Areas.Manage.Controllers
{
    public class FriendController : ManagerControllerBase
    {
        //
        // GET: /Manage/Friends/
        public ActionResult Index(int? page)
        {
            int PageIndex = page == null ? 1 : page.Value;
            int PageSize = 20;
            int RecordCount = 0;
            ViewBag.FriendList = Friend.GetList(PageIndex, PageSize, out RecordCount);

            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Friend friend)
        {
            if (ModelState.IsValid)
            {
                friend.SavePortrait(Request.Files["Portrait"]);
                friend.Create();
                return RedirectToAction("index");
            }

            return View();
        }

        public ActionResult Edit(int id)
        {
            var friend = Friend.Find(id);
            if (friend == null)
                return View("_404");
            
            return View(friend);
        }

        [HttpPost]
        public ActionResult Edit(Friend friend)
        {
            if (ModelState.IsValid)
            {
                var old = Friend.Find(friend.ID);
                if (Request.Files["Portrait"] != null && Request.Files["Portrait"].ContentLength > 0)
                    old.SavePortrait(Request.Files["Portrait"]);

                old.LinkUrl = friend.LinkUrl;
                old.Name = friend.Name;

                old.Update();
                return RedirectToAction("index");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Delete(FormCollection formValues)
        {
            if (!String.IsNullOrEmpty(formValues["id"]))
            {
                var FriendID = Convert.ToInt32(formValues["id"]);
                Friend.Find(FriendID).Delete();
                return Json(new { result = true, message = String.Empty });
            }
            return Json(new { result = false, message = "参数错误" });
        }
    }
}
